package com.neisha.listener;

import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import com.neisha.kit.JobKit;
import com.neisha.kit.JobKit.JobTrigger;

public class TimeContextListener implements ServletContextListener{

	Scheduler scheduler = null;
	
	/**
	 * 项目启动
	 */
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		try{
			scheduler = StdSchedulerFactory.getDefaultScheduler();
			List<JobTrigger> jobs = JobKit.getTriggers();
			if(jobs == null || jobs.size() == 0){
				return ;
			}
			for(JobTrigger item : jobs){
				Trigger trigger = TriggerBuilder.newTrigger()
						.withIdentity("trigger","jobGroup"+item.getName())
						.withSchedule(CronScheduleBuilder.cronSchedule(item.getCron()))
						.build();
				
				JobDetail job = JobBuilder.newJob(item.getCls()).withIdentity(item.getName(),
						"jobGroup"+item.getName()).build();
				scheduler.scheduleJob(job,trigger);
			}
			scheduler.start();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * 项目结束
	 */
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		try {
			scheduler.shutdown();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

}
